//
//  GroupInfoViewController.m
//  zhixinApp
//
//  Created by zhiguanzhl on 2017/11/19.
//  Copyright © 2017年 zhiguanzhl. All rights reserved.
//

#import "GroupInfoViewController.h"
#import "UpImageCell.h"
#import "MemberOneViewController.h"
#import "SBMyWebViewController.h"
#import "MainWebViewController.h"
#import "SelectMemberViewController.h"
#import "GroupSetTableViewCell.h"
#import "CompanyViewController.h"

@interface GroupInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,assign)NSInteger count;
@property (nonatomic,copy)NSString *Name;
@property (nonatomic,copy)NSString *cursor;
@property (nonatomic,assign)bool isCompanyGroup;

//为了给成员列表传，群主这个人你不可以被删掉
@property (nonatomic,strong)NSString *owner;
@property (nonatomic,strong)NSString *companyName;

@end


@implementation GroupInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"群设置";
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.backgroundColor = CViewBgColor;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = [[UIView alloc] init];
    tableView.tableHeaderView = [self headerView];
    [self.view addSubview:tableView];
    self.cursor = @"";
     [self isCompanyGrouop];
    [self loadData];
   
    [self initBottmView];
   

};

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.count = self.occupantArr.count;
    [self.tableView reloadData];
}

- (void)loadData{
    
    EMError *error = nil;
//群组成员需要掉这个方法
    EMCursorResult* result = [[EMClient sharedClient].groupManager getGroupMemberListFromServerWithId:self.conversationId cursor:self.cursor pageSize:50 error:&error];
    self.cursor = result.cursor;
    
    //获取群组详情，只能是获取到群主、和occupantsCount，但occupants里面只有owner一个id
    EMGroup *group = [[EMClient sharedClient].groupManager getGroupSpecificationFromServerWithId:self.conversationId error:nil];

    //获取管理员列表
    self.owner = group.owner;
    //获取群里的所有人列表
    self.count = group.occupantsCount;
    self.groupName = group.subject;
    //！！！此时的group.occupants获得是分页的第一页的数据，并非全部的成员
    NSArray *occupantArr = group.occupants;
    [self.occupantArr addObjectsFromArray:occupantArr];

    NSData *data = [[NSUserDefaults standardUserDefaults]valueForKey:@"numberArr"];
    NSArray *numberSArr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    [self.memeberArr removeAllObjects];
    for (NSString *nameStr in self.occupantArr) {
        NSString *titleName = [Tool getHeadNameWithArr:numberSArr withString:nameStr];

        [self.memeberArr addObject:titleName];
    }
    
    [self.tableView reloadData];
    
}

- (void)isCompanyGrouop{
    
    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
    [paramDict setValue:[DataCenter shareInstence].loginName forKey:@"loginName"];
    NSArray *companyModelArr = [DataCenter shareInstence].companyList;
//    CompanyModel *model = companyModelArr.firstObject;
//    [paramDict setValue:model.companyId forKey:@"companyId"];
    
    for (int i=0; i<companyModelArr.count; i++) {
        
        CompanyModel *model = companyModelArr[i];
        [paramDict setValue:model.companyId forKey:@"companyId"];
        
        
        [ZLHXHelper postURL:@"organization/group" paramDict:paramDict completion:^(NSDictionary *responseObject) {
            NSArray *groupArr = [responseObject valueForKey:@"obj"];
            for (NSDictionary *dic in groupArr) {
                if ([[dic valueForKey:@"groupId"] isEqualToString:self.conversationId]) {
                    NSNumber *groupType = [dic valueForKey:@"groupType"];
                    NSInteger count = [groupType integerValue];
                    if (count == 1 || count == 2) {
                        self.isCompanyGroup = YES;
                    }
                    self.companyName = model.name;
                    
                    break;
                }
            }
            
            self.tableView.tableHeaderView = [self headerView];
            [self.tableView reloadData];
        } error:^(NSError *error) {
            
        }];
        
        
        
    }

}

- (UIView *)headerView
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 170)];
    headerView.backgroundColor = KWhiteColor;
    
    UIButton *userIcon = [[UIButton alloc]initWithFrame:CGRectMake((kSCREEN_WIDTH-75)*0.5, 20, 75, 75)];
    ViewRadius(userIcon ,75*0.5);
    [headerView addSubview:userIcon];
    
    UILabel *namelable = [UILabel labelWithFrame:CGRectMake((kSCREEN_WIDTH-230)*0.5,CGRectGetMaxY(userIcon.frame)+10 , 230, 14) Font:FONT(16) TextColor:[UIColor colorWithHexString:@"454545"]];
    namelable.text = self.groupName;
    namelable.textAlignment = 1;
    [headerView addSubview:namelable];
    
    UILabel *MaskL = [UILabel labelWithFrame:CGRectMake(CGRectGetMaxX(namelable.frame), CGRectGetMaxY(userIcon.frame)+10, 40, 14) Font:FONT(12) TextColor:KWhiteColor];
    ViewRadius(MaskL, 6);
//    MaskL.text = @"公司群";
    [headerView addSubview:MaskL];
    
    UILabel *fullName = [UILabel labelWithFrame:CGRectMake(0,CGRectGetMaxY(namelable.frame)+8 , kSCREEN_WIDTH, 14) Font:FONT(12) TextColor:[UIColor colorWithHexString:@"999999"]];
    fullName.textAlignment = 1;
    fullName.text = self.companyName;
    [headerView addSubview:fullName];
    
    UIView *nillView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(fullName.frame)+21, kSCREEN_WIDTH, 8)];
    nillView.backgroundColor = KLineColor;
    [headerView addSubview:nillView];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerView.frame)-1, kSCREEN_WIDTH, 1)];
    lineView.backgroundColor = KLineColor;
    [headerView addSubview:lineView];
    
    if (self.isCompanyGroup) {
        MaskL.text = @"公司群";
//        fullName.text = [DataCenter shareInstence].companyName;
        [userIcon setImage:[UIImage imageNamed:@"gstb_icon"] forState:(UIControlState)UIControlStateNormal];
        MaskL.backgroundColor = [UIColor colorWithHexString:@"2c9ae8"];
        
    }else{
        MaskL.text = @"";
         MaskL.backgroundColor = KWhiteColor;
//        fullName.text = @"";
        [userIcon setTitle:@"群" forState:UIControlStateNormal];
        userIcon.titleLabel.font = [UIFont boldSystemFontOfSize:28];
        userIcon.backgroundColor = [UIColor colorWithHexString:@"2c9ae8"];
        [userIcon setTitleColor:KWhiteColor forState:UIControlStateNormal];
    }
    
    return headerView;
    
}

- (void)initBottmView{
    
    UIView *footView= [[UIView alloc]initWithFrame:CGRectMake(0,kSCREEN_HEIGHT-72-64, kSCREEN_WIDTH, 72)];
    footView.backgroundColor = KWhiteColor;
    [self.view addSubview:footView];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(15, 10, kSCREEN_WIDTH-30, 52)];
    btn.layer.cornerRadius = 52*0.5;
    btn.layer.masksToBounds = YES;
    btn.backgroundColor = [UIColor colorWithHexString:@"2c9ae8"];
    btn.titleLabel.font = [UIFont systemFontOfSize:18];
    [btn setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(backGroup) forControlEvents:UIControlEventTouchUpInside];
    
     if (self.isAdmin) {
        [btn setTitle:@"解散该群" forState:UIControlStateNormal];
    }else{
        [btn setTitle:@"退出群聊" forState:UIControlStateNormal];
    }
    [footView addSubview:btn];
    
}

//解散该群/退出群聊
- (void)backGroup{
    
    if (self.isAdmin) {//解散
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            EMError *error = nil;
            // 处理耗时操作的代码块
            [[EMClient sharedClient].groupManager destroyGroup:self.conversationId error:&error];
            
                if (!error) {
                    iToast *toast = [[iToast alloc] initWithText:@"解散成功"];
                    [toast show];
                    
            }
            
        });
        
    }else{//退出群聊
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 处理耗时操作的代码块
            EMError *error = nil;
            [[EMClient sharedClient].groupManager leaveGroup:self.conversationId error:&error];
            
            if (!error) {
                iToast *toast = [[iToast alloc] initWithText:@"已经主动退出群聊"];
                [toast show];
                
            }
            
        });
        
        
    }
    
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count;
    if (section == 0) {
        count = 1;
    }else {
        count = 2;
    }
    return count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height;
    if (indexPath.section == 0) {
        height = 120;
    }else{
        height = 44;
    }
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UpImageCell *membersCell = [UpImageCell cellWithTableView:tableView];
//        membersCell.countL.text = [NSString stringWithFormat:@"%ld",self.occupantArr.count];
        membersCell.countL.text = [NSString stringWithFormat:@"%ld",self.count];

        //对collectionView的展示切割名字
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        
        for (NSString *str in self.memeberArr) {
            NSString *subStr;
            if (str.length>2) {
            subStr = [str substringFromIndex:1];
                
            }else{
                subStr = str;
            }
            
            [arr addObject:subStr];
        }
        
        if (_isAdmin && !_isCompanyGroup) {
            
            if (arr.count <= 4) {
                [arr addObject:@"+"];
                [arr addObject:@"-"];
            }else{
                
                arr = [[arr subarrayWithRange:NSMakeRange(0, 4)] mutableCopy];
                [arr addObject:@"+"];
                [arr addObject:@"-"];
                
            }
        }else{
            
            if (arr.count <= 5) {
                [arr addObject:@"..."];
            }else{
                
                arr = [[arr subarrayWithRange:NSMakeRange(0, 5)] mutableCopy];
                [arr addObject:@"..."];
                
            }
            
        }
        
        membersCell.nameArray = arr;

        membersCell.block = ^(NSInteger collctionItem){
            if (self.isAdmin) {
                //是管理员
                if (collctionItem == arr.count-2) {
                    //添加人
//                    NSLog(@"添加人");
                    
                    CompanyViewController *vc = [[CompanyViewController alloc] init];
//                    //加的人传给后台
                    vc.conversationId = self.conversationId;
//                    //把群组里的人全部传给了选择的人用来做标记
                    vc.occupanys = self.occupantArr;
                    [self.navigationController pushViewController:vc animated:YES];
                    
                    
//                SelectMemberViewController *selectVC = [[SelectMemberViewController alloc] init];
//                selectVC.conversationId = self.conversationId;
                //把群组里的人全部传给了选择的人用来做标记
//                selectVC.occupanys = self.occupantArr;
//                [self.navigationController pushViewController:selectVC animated:YES];
                    
                }else if (collctionItem == arr.count-1){
                     NSLog(@"减人");
                    MemberOneViewController *memberVC = [[MemberOneViewController alloc] init];
                    
                    memberVC.conversationId
                    = self.conversationId;
                    
                    memberVC.block = ^(NSMutableArray *memberArr, NSMutableArray *logaiNameArr) {
                                            self.memeberArr =[memberArr mutableCopy];
                                            self.occupantArr =[logaiNameArr mutableCopy];
                        [self.occupantArr insertObject:self.owner atIndex:0];
                        NSString * chinaOwer = [Tool unChiveWithString:self.owner];
                        [self.memeberArr insertObject:chinaOwer atIndex:0];
                                            [self.tableView reloadData];
                                        };
                 
//                    memberVC.memberArr = [self.memeberArr mutableCopy];
//                    memberVC.logaiNameArr = [self.occupantArr mutableCopy];
                    [self.navigationController pushViewController:memberVC animated:YES];
                
                }
            }else{
                if (collctionItem == arr.count-1){
                    //查看全部成员
                    MemberOneViewController *memberVC = [[MemberOneViewController alloc] init];
//                    memberVC.groupName = self.groupName;
                    memberVC.conversationId = self.conversationId;
                    memberVC.isCompany = self.isCompanyGroup;
                    memberVC.notAdmin = YES;
                    memberVC.owner = self.owner;
//                    memberVC.memberArr = [self.memeberArr mutableCopy];
//                    memberVC.logaiNameArr = [self.occupantArr
//                                             mutableCopy];
                    [self.navigationController pushViewController:memberVC animated:YES];
                    return ;
                }else{
                    NSLog(@"不可以选");
                    return;
                
                }
                
            }
            
        };
        
        return membersCell;
    }else{
        
        GroupSetTableViewCell *groupSetCell = [GroupSetTableViewCell cellWithTableView:tableView];
        if (indexPath.row == 0) {
            groupSetCell.titleName.text = @"消息免打扰";
            groupSetCell.block = ^(BOOL isOn) {
                
                [self swithActionWithState:isOn];
            };
        }else{
            
            groupSetCell.titleName.text = @"清空聊天记录";
            groupSetCell.swichView.hidden = YES;
        }
        return groupSetCell;
    }
    
}

- (void)swithActionWithState:(BOOL)state{
    
    if (state) {
        if (_isAdmin) {
            [self showAlert:@"您是群主不可以屏蔽群消息"];
        }else{
            [[EMClient sharedClient].groupManager blockGroup:self.conversationId completion:^(EMGroup *aGroup, EMError *aError) {
                if (!aError) {
                    
                    [self showAlert:@"消息已经屏蔽"];
                    
                }
            }];
        }
    }else{
        
        [[EMClient sharedClient].groupManager unblockGroup:self.conversationId completion:^(EMGroup *aGroup, EMError *aError) {
            
            [self showAlert:@"消息屏蔽已经取消"];
            
        }];
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        
        //查看全部成员
        MemberOneViewController *memberVC = [[MemberOneViewController alloc] init];
        memberVC.notAdmin = YES;
        memberVC.conversationId = self.conversationId;
//        memberVC.memberArr = self.memeberArr;
//        memberVC.logaiNameArr = self.occupantArr;
        memberVC.owner = self.owner;
        [self.navigationController pushViewController:memberVC animated:YES];
        
    }else{
        if (indexPath.row == 1) {//清空聊天记录
            
            [self alertWithTitle:@"提示" message:@"是否清空聊天记录？" Completion:^{
                
                //发个通知
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RemoveAllMessages" object:self.conversationId];
                
               EMConversation *convisation =  [[EMClient sharedClient].chatManager getConversation:self.conversationId type:(EMConversationType)EMConversationTypeGroupChat createIfNotExist:YES];
//                删除该会话所有消息，同时清除内存和数据库中的消息
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                [convisation deleteAllMessages:nil];
                    
                     });
                
            }];
            
        }
        
    }

    
}

- (NSMutableArray *)memeberArr{
    if (!_memeberArr) {
        _memeberArr = [[NSMutableArray alloc] init];
    }
    return _memeberArr;
}
- (NSMutableArray *)occupantArr{
    if (!_occupantArr) {
        _occupantArr = [[NSMutableArray alloc] init];
    }
    return _occupantArr;
}
@end
